<template>
  <PageWrapper :contentFullHeight="true">
    <div class="card-container">
      <Card>
        <div class="public-account-management clearfix" v-loading="data.loading">
          <!--左边配置菜单-->
          <div class="left">
            <div class="weixin-hd">
              <div class="weixin-title">{{ data.name }}</div>
            </div>

            <div class="weixin-menu menu_main clearfix">
              <div class="menu_bottom" v-for="(item, i) of data.menuList" :key="i">
                <!-- 一级菜单 -->
                <div @click="menuClick(i, item)" class="menu_item" :class="{ active: data.isActive === i }">
                  {{ item.name }}
                </div>

                <!-- 以下为二级菜单-->
                <div class="submenu" v-if="data.isSubMenuFlag === i">
                  <div class="subtitle menu_bottom" v-if="item.children" v-for="(subItem, k) in item.children" :key="k">
                    <div class="menu_subItem" :class="{ active: data.isSubMenuActive === i + '' + k }" @click="subMenuClick(subItem, i, k)">
                      {{ subItem.name }}
                    </div>
                  </div>

                  <!-- 二级菜单加号， 当长度 小于 5 才显示二级菜单的加号  -->
                  <div class="menu_bottom menu_addicon" v-if="!item.children || item.children.length < 5" @click="addSubMenu(i, item)">
                    <Icon icon="i-ant-design:plus-outlined" />
                  </div>
                </div>
              </div>

              <!-- 一级菜单加号 -->
              <div class="menu_bottom menu_addicon" v-if="data.menuList.length < 3" @click="addMenu">
                <Icon icon="i-ant-design:plus-outlined" />
              </div>
            </div>

            <div class="save_div">
              <a-button class="save_btn" type="primary" @click="handleSave">保存并发布菜单</a-button>
              <a-button class="save_btn" type="primary" danger @click="handleDelete">清空菜单</a-button>
            </div>
          </div>

          <!--右边配置-->
          <div v-if="data.showRightFlag" class="right">
            <div class="configure_page">
              <div class="delete_btn">
                <a-button size="small" type="danger" preIcon="ant-design:delete-outlined" @click="deleteMenu(data.tempObj)"> 删除当前菜单 </a-button>
              </div>

              <div>
                <span>菜单名称：</span>
                <a-input
                  class="input_width"
                  v-model:value="data.tempObj.name"
                  placeholder="请输入菜单名称"
                  :maxlength="data.nameMaxLength"
                  allow-clear
                />
              </div>

              <div v-if="data.showConfigureContent">
                <div class="menu_item">
                  <span>菜单标识：</span>
                  <a-input class="input_width" v-model:value="data.tempObj.menuKey" placeholder="请输入菜单 KEY" allow-clear />
                </div>
                <div class="menu_content menu_item">
                  <span>菜单内容：</span>
                  <a-select show-search v-model:value="data.tempObj.type" allow-clear placeholder="请选择" class="menu_option">
                    <a-select-option v-for="item in data.menuOptions" :label="item.label" :value="item.value" :key="item.value">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>

                  <div class="configur_content menu_item" style="width: 100%" v-if="data.tempObj.type === 'view'">
                    <span>跳转链接：</span>
                    <a-input class="input_width" v-model:value="data.tempObj.url" placeholder="请输入链接" allow-clear />
                  </div>
                  <div class="configur_content" v-if="data.tempObj.type === 'miniprogram'">
                    <div class="applet">
                      <span>小程序的 appid ：</span>
                      <a-input class="input_width" v-model:value="data.tempObj.miniProgramAppId" placeholder="请输入小程序的appid" allow-clear />
                    </div>
                    <div class="applet">
                      <span>小程序的页面路径：</span>
                      <a-input
                        class="input_width"
                        v-model:value="data.tempObj.miniProgramPagePath"
                        placeholder="请输入小程序的页面路径，如：pages/index"
                        allow-clear
                      />
                    </div>
                    <div class="applet">
                      <span>小程序的备用网页：</span>
                      <a-input
                        class="input_width"
                        v-model:value="data.tempObj.url"
                        placeholder="不支持小程序的老版本客户端将打开本网页"
                        allow-clear
                      />
                    </div>
                    <p class="blue">tips:需要和公众号进行关联才可以把小程序绑定带微信菜单上哟！</p>
                  </div>

                  <div class="configur_content" v-if="data.tempObj.type === 'article_view_limited'">
                    <a-row>
                      <div class="select-item" v-if="data.tempObj && data.tempObj.replyArticles">
                        <WxNews :articles="data.tempObj.replyArticles" />
                        <a-row class="ope-row">
                          <a-button type="danger" preIcon="ant-design:delete-outlined" @click="deleteMaterial" />
                        </a-row>
                      </div>
                      <div v-else>
                        <a-row>
                          <a-col :span="24" style="text-align: center">
                            <a-button type="success" @click="openMaterial"> 素材库选择 </a-button>
                          </a-col>
                        </a-row>
                      </div>
                      <!-- <el-dialog title="选择图文" :visible.sync="data.dialogNewsVisible" width="90%"> -->
                      <!-- <wx-material-select :objData="{type: 'news'}" @selectMaterial="selectMaterial" /> -->
                      <!-- </el-dialog> -->
                    </a-row>
                  </div>

                  <div class="configur_content" v-if="data.tempObj.type === 'click' || data.tempObj.type === 'scancode_waitmsg'">
                    <WxReply :objData="data.tempObj.reply" v-if="data.hackResetWxReplySelect" />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 一进页面就显示的默认页面，当点击左边按钮的时候，就不显示了-->
          <div v-else class="right">
            <p>请选择菜单配置</p>
          </div>
        </div>
      </Card>
    </div>
  </PageWrapper>
</template>

<script lang="ts" name="weixin-mp-menu" setup>
  import { ref, computed, onMounted, unref, useAttrs, reactive } from "vue"
  import { PageWrapper } from "/@/components/Page"
  import { Card } from "ant-design-vue"
  import { releaseMenu, listMenu, deleteMenu as deleteMpMenu } from "./api"
  import { useMessage } from "/@/hooks/web/useMessage"
  import WxNews from "/@/views/channel/wxMp/components/WxNews/index.vue"
  import WxReply from "/@/views/channel/wxMp/components/WxReply/index.vue"
  import { listToTree } from "/@/utils/common/compUtils"
  import { any } from "vue-types"
  import { Icon } from "/@/components/Icon"

  const { createConfirm, createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const data = reactive<any>({
    // ======================== 列表查询 ========================
    // 遮罩层
    loading: false,
    // 显示搜索条件
    showSearch: true,
    name: "", // 公众号名
    menuList: [],

    // ======================== 菜单操作 ========================
    isActive: -1, // 一级菜单点中样式
    isSubMenuActive: -1, // 一级菜单点中样式
    isSubMenuFlag: -1, // 二级菜单显示标志

    // ======================== 菜单编辑 ========================
    showRightFlag: false, // 右边配置显示默认详情还是配置详情
    nameMaxLength: 0, // 菜单名称最大长度；1 级是 4 字符；2 级是 7 字符；
    showConfigureContent: true, // 是否展示配置内容；如果有子菜单，就不显示配置内容
    hackResetWxReplySelect: true, // 重置 WxReplySelect 组件
    tempObj: {
      // 右边临时变量，作为中间值牵引关系
      reply: {},
    },
    tempSelfObj: {
      // 一些临时值放在这里进行判断，如果放在 tempObj，由于引用关系，menu 也会多了多余的参数
      index: 0,
    },
    dialogNewsVisible: false, // 跳转图文时的素材选择弹窗
    menuOptions: [
      {
        value: "view",
        label: "跳转网页",
      },
      {
        value: "miniprogram",
        label: "跳转小程序",
      },
      {
        value: "click",
        label: "点击回复",
      },
      {
        value: "article_view_limited",
        label: "跳转图文消息",
      },
      {
        value: "scancode_push",
        label: "扫码直接返回结果",
      },
      {
        value: "scancode_waitmsg",
        label: "扫码回复",
      },
      {
        value: "pic_sysphoto",
        label: "系统拍照发图",
      },
      {
        value: "pic_photo_or_album",
        label: "拍照或者相册",
      },
      {
        value: "pic_weixin",
        label: "微信相册",
      },
      {
        value: "location_select",
        label: "选择地理位置",
      },
    ],

    // 公众号账号列表
    accounts: [],
  })

  onMounted(() => {
    getList()
  })

  const getList = async () => {
    const retData = await listMenu({})
    const newData = convertMenuList(retData)
    data.menuList = listToTree(newData, { primaryKey: "id" }, "0")
    console.log("menuList: ", data.menuList)
  }

  // ======================== 菜单操作 ========================
  // 一级菜单点击事件
  const menuClick = (i, item) => {
    // 右侧的表单相关
    //  resetEditor();
    data.showRightFlag = true // 右边菜单
    data.tempObj = item // 这个如果放在顶部，flag 会没有。因为重新赋值了。
    data.tempSelfObj.grand = "1" // 表示一级菜单
    data.tempSelfObj.index = i // 表示一级菜单索引
    data.nameMaxLength = 4
    data.showConfigureContent = !(item.children && item.children.length > 0) // 有子菜单，就不显示配置内容

    // 左侧的选中
    data.isActive = i // 一级菜单选中样式
    data.isSubMenuFlag = i // 二级菜单显示标志
    data.isSubMenuActive = -1 // 二级菜单去除选中样式
  }
  // 二级菜单点击事件
  const subMenuClick = (subItem, index, k) => {
    // 右侧的表单相关
    // data.resetEditor();
    data.showRightFlag = true // 右边菜单
    data.tempObj = subItem // 将点击的数据放到临时变量，对象有引用作用
    data.tempSelfObj.grand = "2" // 表示二级菜单
    data.tempSelfObj.index = index // 表示一级菜单索引
    data.tempSelfObj.secondIndex = k // 表示二级菜单索引
    data.nameMaxLength = 7
    data.showConfigureContent = true

    // 左侧的选中
    data.isActive = -1 // 一级菜单去除样式
    data.isSubMenuActive = index + "" + k // 二级菜单选中样式
  }
  // 添加横向一级菜单
  const addMenu = () => {
    const menuKeyLength = data.menuList.length
    const addButton = {
      name: "菜单名称",
      children: [],
      reply: {
        // 用于存储回复内容
        type: "text",
      },
    }

    data.menuList.push(addButton)
    console.log("menu: ", data.menuList)
    // data.$set(data.menuList, menuKeyLength, addButton)
    menuClick(data.menuKeyLength - 1, addButton)
  }
  // 添加横向二级菜单；item 表示要操作的父菜单
  const addSubMenu = (i, item) => {
    // 清空父菜单的属性，因为它只需要 name 属性即可
    if (!item.children || item.children.length <= 0) {
      item.children = []
      delete item.type
      delete item.menuKey
      delete item.miniProgramAppId
      delete item.miniProgramPagePath
      delete item.url
      delete item.articleId
      delete item.replyArticles
      delete item.reply
      // 关闭配置面板
      data.showConfigureContent = false
    }

    let subMenuKeyLength = item.children.length // 获取二级菜单key长度
    let addButton = {
      name: "子菜单名称",
      reply: {
        // 用于存储回复内容
        type: "text",
      },
    }
    item.children.push(addButton)
    subMenuClick(item.children[subMenuKeyLength], i, subMenuKeyLength)
    console.log("menu: ", data.menuList)
  }

  // 重置表单，清空表单数据
  const resetForm = () => {
    // 菜单操作
    data.isActive = -1
    data.isSubMenuActive = -1
    data.isSubMenuFlag = -1

    // 菜单编辑
    data.showRightFlag = false
    data.nameMaxLength = 0
    data.showConfigureContent = 0
    data.hackResetWxReplySelect = true
    data.hackResetWxReplySelect = false
    data.tempObj = {
      reply: {},
    }
    data.tempSelfObj = {}
    data.dialogNewsVisible = false
  }

  // ======================== 菜单编辑 ========================
  const handleSave = () => {
    createConfirm({
      iconType: "warning",
      title: "提示",
      content: "确定要保证并发布该菜单吗？",
      onOk: () => {
        data.loading = true
        const menus = convertMenuFormList()
        releaseMenu({ menus })
          .then(() => {
            createMessage.success("发布成功")
          })
          .finally(() => {
            data.loading = false
          })
        console.log("menu: ", menus)
      },
    })
  }

  // 将前端的 menuList，转换成后端接收的 menuList
  const convertMenuFormList = () => {
    const menuList: any = []
    data.menuList.forEach((item) => {
      let menu = convertMenuForm(item)
      menuList.push(menu)
      // 处理子菜单
      if (!item.children || item.children.length <= 0) {
        return
      }
      menu.children = []
      item.children.forEach((subItem) => {
        menu.children.push(convertMenuForm(subItem))
      })
    })
    return menuList
  }
  // 将前端的 menu，转换成后端接收的 menu
  const convertMenuForm = (menu) => {
    let result = {
      ...menu,
      children: undefined, // 不处理子节点
      reply: undefined, // 稍后复制
    }
    if (menu.type === "click" || menu.type === "scancode_waitmsg") {
      result.replyMessageType = menu.reply.type
      result.replyContent = menu.reply.content
      result.replyMediaId = menu.reply.mediaId
      result.replyMediaUrl = menu.reply.url
      result.replyTitle = menu.reply.title
      result.replyDescription = menu.reply.description
      result.replyThumbMediaId = menu.reply.thumbMediaId
      result.replyThumbMediaUrl = menu.reply.thumbMediaUrl
      result.replyArticles = menu.reply.articles
      result.replyMusicUrl = menu.reply.musicUrl
      result.replyHqMusicUrl = menu.reply.hqMusicUrl
    }
    return result
  }

  // 表单 Editor 重置
  const resetEditor = () => {
    // this.hackResetWxReplySelect = false // 销毁组件
    // this.$nextTick(() => {
    //   this.hackResetWxReplySelect = true // 重建组件
    // })
  }
  const handleDelete = () => {
    createConfirm({
      iconType: "warning",
      title: "提示",
      content: "确定要清空所有菜单吗？",
      onOk: () => {
        data.loading = true
        deleteMpMenu({})
          .then(() => {
            createMessage.success("删除成功")
            data.menuList = []
            resetForm()
          })
          .finally(() => {
            data.loading = false
          })
      },
    })
  }

  // 删除当前菜单
  const deleteMenu = (item) => {
    createConfirm({
      iconType: "warning",
      title: "提示",
      content: "确定要删除吗",
      onOk: () => {
        // 删除数据
        if (data.tempSelfObj.grand === "1") {
          // 一级菜单的删除方法
          data.menuList.splice(data.tempSelfObj.index, 1)
        } else if (data.tempSelfObj.grand === "2") {
          // 二级菜单的删除方法
          data.menuList[data.tempSelfObj.index].children.splice(data.tempSelfObj.secondIndex, 1)
        }
        // 提示
        createMessage.success("删除成功")

        // 处理菜单的选中
        data.tempObj = {}
        data.showRightFlag = false
        data.isActive = -1
        data.isSubMenuActive = -1
      },
    })
  }

  // 将后端返回的 menuList，转换成前端的 menuList
  const convertMenuList = (list) => {
    const menuList: any = []
    list.forEach((item) => {
      const menu = {
        ...item,
      }
      if (item.type === "click" || item.type === "scancode_waitmsg") {
        delete menu.replyMessageType
        delete menu.replyContent
        delete menu.replyMediaId
        delete menu.replyMediaUrl
        delete menu.replyDescription
        delete menu.replyArticles

        menu.reply = {
          type: item.replyMessageType,
          content: item.replyContent,
          mediaId: item.replyMediaId,
          url: item.replyMediaUrl,
          title: item.replyTitle,
          description: item.replyDescription,
          thumbMediaId: item.replyThumbMediaId,
          thumbMediaUrl: item.replyThumbMediaUrl,
          articles: item.replyArticles,
          musicUrl: item.replyMusicUrl,
          hqMusicUrl: item.replyHqMusicUrl,
        }
      }
      menuList.push(menu)
    })
    return menuList
  }

  // ======================== 菜单编辑（素材选择） ========================
  const openMaterial = () => {
    data.dialogNewsVisible = true
  }
  const deleteMaterial = () => {
    delete data.tempObj.articleId
    delete data.tempObj.replyArticles
  }
</script>

<style lang="less" scoped="scoped">
  .card-container {
    margin-top: 15px;
  }

  .card {
    margin-bottom: -20px;
  }

  /* 公共颜色变量 */
  .clearfix {
    *zoom: 1;
  }

  .clearfix::after {
    content: "";
    display: table;
    clear: both;
  }

  div {
    text-align: left;
  }

  .weixin-hd {
    color: #fff;
    text-align: center;
    position: relative;
    bottom: 426px;
    left: 0px;
    width: 300px;
    height: 64px;
    background: transparent url("assets/menu_head.png") no-repeat 0 0;
    background-position: 0 0;
    background-size: 100%;
  }

  .weixin-title {
    color: #fff;
    font-size: 14px;
    width: 100%;
    text-align: center;
    position: absolute;
    top: 33px;
    left: 0px;
  }

  .weixin-menu {
    background: transparent url("assets/menu_foot.png") no-repeat 0 0;
    padding-left: 43px;
    font-size: 12px;
  }

  .menu_option {
    width: 50% !important;
  }

  .public-account-management {
    min-width: 1200px;
    width: 1200px;
    height: 100%;
    margin: 0 auto;

    .left {
      float: left;
      display: inline-block;
      width: 350px;
      height: 715px;
      background: url("assets/iphone_backImg.png") no-repeat;
      background-size: 100% auto;
      padding: 518px 25px 88px;
      position: relative;
      box-sizing: border-box;

      /*第一级菜单*/
      .menu_main {
        .menu_bottom {
          position: relative;
          float: left;
          display: inline-block;
          box-sizing: border-box;
          width: 85.5px;
          text-align: center;
          border: 1px solid #ebedee;
          background-color: #fff;
          cursor: pointer;

          &.menu_addicon {
            height: 46px;
            line-height: 46px;
          }

          .menu_item {
            height: 44px;
            line-height: 44px;
            text-align: center;
            box-sizing: border-box;
            width: 100%;

            &.active {
              border: 1px solid #2bb673;
            }
          }

          .menu_subItem {
            height: 44px;
            line-height: 44px;
            text-align: center;
            box-sizing: border-box;

            &.active {
              border: 1px solid #2bb673;
            }
          }
        }

        i {
          color: #2bb673;
        }

        /*第二级菜单*/
        .submenu {
          position: absolute;
          width: 85.5px;
          bottom: 45px;

          .subtitle {
            background-color: #fff;
            box-sizing: border-box;
          }
        }
      }

      .save_div {
        margin-top: 15px;
        text-align: center;

        .save_btn {
          bottom: 20px;

          margin: 20px 10px 10px 10px;
        }
      }
    }

    /*右边菜单内容*/
    .right {
      float: left;
      width: 63%;
      background-color: @content-bg;
      padding: 20px;
      border-radius: 10px;
      margin-left: 20px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;

      .configure_page {
        .delete_btn {
          text-align: right;
          margin-bottom: 15px;
        }

        .menu_item {
          margin-top: 20px;
        }

        .menu_content {
          .input_width {
            width: 80%;
          }
        }

        .configur_content {
          background-color: #fff;
          padding: 20px 10px;
          border-radius: 5px;
        }

        .blue {
          color: #29b6f6;
          margin-top: 10px;
        }

        .applet {
          margin-bottom: 20px;

          span {
            width: 50%;
          }
        }

        .input_width {
          width: 50%;
        }

        .material {
          .input_width {
            width: 30%;
          }

          .el-textarea {
            width: 80%;
          }
        }
      }
    }

    .el-input {
      width: 70%;
      margin-right: 2%;
    }
  }

  .pagination {
    text-align: right;
    margin-right: 25px;
  }

  .select-item {
    width: 280px;
    padding: 10px;
    margin: 0 auto 10px auto;
    border: 1px solid #eaeaea;
  }

  .select-item2 {
    padding: 10px;
    margin: 0 auto 10px auto;
    border: 1px solid #eaeaea;
  }

  .ope-row {
    padding-top: 10px;
    text-align: center;
  }

  .item-name {
    font-size: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }
</style>
